package com.lysj.bhp.scheduled.job;

import com.google.gson.Gson;
import com.lysj.bhp.scheduled.base.ScheduledContent;
import com.lysj.bhp.scheduled.domain.BuWallet;
import com.lysj.bhp.scheduled.domain.RechargeRecord;
import com.lysj.bhp.util.http.HttpUtil;
import com.lysj.bhp.util.json.bubalance.JsonRootBean;
import com.lysj.bhp.util.json.bubalance.Result;
import com.lysj.bhp.util.web.ParamUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;

@Component
public class BuWalletJob extends ScheduledContent {
    private static Logger logger = LoggerFactory.getLogger(BuWalletJob.class);
    private static String BU_BALANCE_URL = "http://seed1.bumo.io:16002/getAccount";
   // private static String BU_TEST_BALANCE_URL = "http://seed1.bumotest.io:26002/getAccount";

    /*第一次10秒后执行，当执行完后0.5秒再执行，保证一秒并发不超过5个*/
    @Scheduled(initialDelay = 10000, fixedDelay = 60000)
    public void queryEthereumWallet() {
        logger.info("BuWalletJob is Starting ...");
        BuWallet buWallet = buWalletRepository.findFirstByOrderByLastQueryTimeAsc();
        if (buWallet == null) {
            return;
        }
        String respJson = HttpUtil.sendGet(BU_BALANCE_URL, "address=" + buWallet.getAddress());//查询bu钱包的可用余额
        if (ParamUtil.isBlack(respJson)) {
            buWallet.setLastQueryTime(System.currentTimeMillis());
            buWalletRepository.save(buWallet);
            logger.error("网络错误:");
            return;
        }
        JsonRootBean jsonRootBean = new Gson().fromJson(respJson, JsonRootBean.class);
        if (jsonRootBean == null) {
            buWallet.setLastQueryTime(System.currentTimeMillis());
            buWalletRepository.save(buWallet);
            logger.error("Json格式化错误:" + buWallet.getBuWalletId());
            return;
        }
        if (jsonRootBean.getError_code() != 0) {
            buWallet.setLastQueryTime(System.currentTimeMillis());
            buWalletRepository.save(buWallet);
            logger.error("接口返回编码错误:"+ buWallet.getBuWalletId());
            return;
        }
        Result result = jsonRootBean.getResult();
        if (result == null) {
            buWallet.setLastQueryTime(System.currentTimeMillis());
            buWalletRepository.save(buWallet);
            logger.error("接口返回结果数据错误:"+ buWallet.getBuWalletId());
            return;
        }
        Long balance = result.getBalance();
        if (balance == null) {
            buWallet.setLastQueryTime(System.currentTimeMillis());
            buWalletRepository.save(buWallet);
            logger.error("余额数据错误:"+ buWallet.getBuWalletId());
            return;
        }

        BigDecimal realBalance = new BigDecimal(balance);
        if (realBalance.compareTo(new BigDecimal(BigInteger.ZERO)) <= -1) { // !!!即使发生错误,也应该继续执行下一次的查询!!!
            logger.error("BuWalletJob return -1,buWalletId is " + buWallet.getBuWalletId());
            buWallet.setLastQueryTime(System.currentTimeMillis());
            buWalletRepository.save(buWallet);
            return;
        }
        //返回真实余额,除以10^8;
        realBalance = realBalance.divide(new BigDecimal("100000000"),8,BigDecimal.ROUND_DOWN);
        if (realBalance.compareTo(buWallet.getBookKeepBalance()) >= 1) { //查询到的余额大于钱包得真实余额(记账余额)，则更新
            logger.info("BuWallet Balance Increment,Start Record!" + buWallet.getBuWalletId());
            BigDecimal increase = realBalance.subtract(buWallet.getBookKeepBalance()); // 增加的余额
            buWallet.setBalance(buWallet.getBalance().add(increase));//更新钱包的总额
            buWallet.setAvailBalance(buWallet.getAvailBalance().add(increase));//更新钱包的可用余额
            // 创建充值记录
            RechargeRecord rechargeRecord = new RechargeRecord();
            rechargeRecord.setCoinType(40);
            rechargeRecord.setPayAmount(increase);
            rechargeRecord.setUserId(buWallet.getUserId());
            rechargeRecord.setCreateTime(new Date());
            rechargeRecord.setAuthentication("成功");
            rechargeRecord.setName("BU");
            rechargeRecord.setChineseName("布");
            rechargeRecord.setAddress("0x" + buWallet.getAddress());
            rechargeRecordRepository.save(rechargeRecord);
        }
        buWallet.setBookKeepBalance(realBalance);//更新钱包的记账余额
        buWallet.setLastQueryTime(System.currentTimeMillis()); // 将最近的查询时间设置为现在
        buWalletRepository.save(buWallet);
    }




}
